package com.culture.bootdemo.utils.fileutils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.culture.bootdemo.common.exception.BusinessException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wen
 * @date 2020/1/16 17:38
 * @Description 读取Excel文件
 **/
@Slf4j
public class EasyExcelUtil {

    /**
     * @param inputStream
     * @param c
     * @param sheetNum    读取第几个sheet，默认为0
     * @param rowNumber   读取行数，默认为1
     * @param validHead   是否校验表头
     * @param <T>
     * @return
     */
    public static <T> List<T> readExcel(InputStream inputStream, Class<T> c, int sheetNum, int rowNumber, boolean validHead) {
        ExcelListener<T> excelListener = new ExcelListener<>();
        excelListener.setValidHead(validHead);
        EasyExcel.read(inputStream, c, excelListener).sheet(sheetNum).headRowNumber(rowNumber).doRead();
        return excelListener.getList();
    }

    private static class ExcelListener<T> extends AnalysisEventListener<T> {
        @Getter
        private final List<T> list = new ArrayList<>();
        private final long startTime = System.currentTimeMillis();

        @Getter
        @Setter
        private boolean validHead;

        @Override
        public void invoke(T o, AnalysisContext analysisContext) {
            list.add(o);
        }


        AtomicInteger indexNum = new AtomicInteger(0);

        /**
         * 校验表头
         *
         * @param headMap
         * @param context
         */
        @Override
        public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
            if (validHead) {
                indexNum.incrementAndGet();
                if (indexNum.get() == 2) {
                    //读取第2行的表头
                    if (!headMap.get(0).equals("姓名")) {
                        throw new BusinessException("模板不正确");
                    }
                }
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            log.info("读取Excel完毕   总行数:{}  耗时:{}毫秒", analysisContext.readRowHolder().getRowIndex(), System.currentTimeMillis() - startTime);
        }

    }
}
